package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.entity.WmUser;
import com.heima.user.feign.ArticleClient;
import com.heima.user.feign.MediaClient;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-07
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    IApUserService userService;

    @Autowired
    MediaClient mediaClient;

    @Autowired
    ArticleClient articleClient;

    //查询认证列表
    @Override
    public ResponseResult<List<ApUserRealname>> listByName(AuthDto dto) {
        //判断状态不为空的话，添加状态查询条件
        IPage<ApUserRealname> pageParam = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> qw = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            qw.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //按照创建时间倒序排列
        qw.orderByDesc(ApUserRealname::getCreatedTime);
        //分页查询
        IPage<ApUserRealname> iPage = this.page(pageParam, qw);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }

    /**
     * 认证审核
     * @param dto
     * @param type 1：通过 0：驳回
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult auth(AuthDto dto, int type) {
        //判断用户审核失败
        //修改认证表状态为2，审核失败，记录驳回原因
        //根据认证id查询认证表
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (type == 0) {
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);
        } else {
            //审核通过
            //查询用户注册信息表
            ApUser apUser = userService.getById(apUserRealname.getUserId());
            //创建自媒体用户
            WmUser wmUser = createWmUser(apUser);
            //创建文章作者
            if (wmUser != null) {
                ApAuthor apAuthor = createAuthor(apUser,wmUser);
                if (apAuthor != null) {
                    //更新自媒体账号中的作者id
                    wmUser.setApAuthorId(apAuthor.getId());
                    mediaClient.saveWmUser(wmUser);
                    //更新认证表的状态为9 审核通过
                    apUserRealname.setStatus(9);
                    this.updateById(apUserRealname);
                    //更新用户注册表中的标识为1，自媒体人
                    apUser.setFlag(1);
                    userService.updateById(apUser);
                }
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 创建作者账号
     * @param apUser
     * @param wmUser
     * @return
     */
    private ApAuthor createAuthor(ApUser apUser, WmUser wmUser) {
        //构建作者的信息
        ApAuthor author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setWmUserId(wmUser.getId());
        ResponseResult<ApAuthor> responseResult = articleClient.saveApAuthor(author);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            return apAuthor;
        } else {
            throw new RuntimeException("调用文章服务失败");
        }
    }

    /**
     * 创建自媒体账号
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        WmUser wmUser = new WmUser();
        //基础信息从apUser赋值
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setId(null);
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        ResponseResult<WmUser> responseResult = mediaClient.saveWmUser(wmUser);
        //判断远程调用的结果
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser user = responseResult.getData();
            return user;
        } else {
            throw new RuntimeException("调用媒体服务失败");
        }
    }
}
